package com.uit.ecommerce.servlets;

import com.uit.ecommerce.bo.AreaBO;
import com.uit.ecommerce.bo.CityBO;
import com.uit.ecommerce.bo.WeatherCityBO;
import com.uit.ecommerce.dto.AreaDTO;
import com.uit.ecommerce.dto.CityDTO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ngloc_it
 */
@WebServlet(name="DetailArea", urlPatterns={"/DetailArea"})
public class DetailArea extends HttpServlet {
   
   // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        PrintWriter out = resp.getWriter();
        String selectArea = (String)req.getParameter("area");
        String function = (String)req.getParameter("function");

        String path = "./jsps/ChiTietKhuVuc.jsp";

        if(function.equalsIgnoreCase("reloadcity")){
            try {
                reloadCity(selectArea, resp);
            } catch (Exception ex) {
                Logger.getLogger(DetailArea.class.getName()).log(Level.SEVERE, null, ex);
            }
            return;
        }else if(function.equalsIgnoreCase("add")){
            try {
                addCity(req, resp);
            } catch (Exception ex) {
                Logger.getLogger(DetailArea.class.getName()).log(Level.SEVERE, null, ex);
            }
            return;
        }else if(function.equalsIgnoreCase("delete")){
            try {
                selectArea = deleteCity(req);
            } catch (Exception ex) {
                Logger.getLogger(DetailArea.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            ArrayList<String> listAreaName = (ArrayList<String>) getListArea(selectArea);
            ArrayList<String> listCity = getListCity(selectArea);
            if(listAreaName != null)
                session.setAttribute("listareaname", listAreaName);
            if(listCity != null)
                session.setAttribute("listcityname", listCity);
        } catch (Exception ex) {
            Logger.getLogger(DetailArea.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        resp.sendRedirect(path);
    }

    private ArrayList<String> getListArea(String selectedArea) throws Exception{
        ArrayList<String> results = new ArrayList<String>();
        if(selectedArea != null)
            results.add(selectedArea);
        AreaBO areaBo = new AreaBO();
        ArrayList<AreaDTO> listArea = areaBo.getAllArea();
        if(listArea != null){
            int n = listArea.size();
            for(int i = 0; i < n; i++){
                String currentArea = "";
                if(!(currentArea = listArea.get(i).getName()).equalsIgnoreCase(selectedArea)){
                    results.add(currentArea);
                }
            }
        }
        return results;
    }

    private ArrayList<String> getListCity(String areaName) throws Exception{
        ArrayList<String> results = new ArrayList<String>();

        CityBO cityBo = new CityBO();
        ArrayList<CityDTO> listCity = cityBo.GetAllCityByAreaName(areaName);
        if(listCity != null){
            int n = listCity.size();
            for(int i = 0; i < n; i++){
                results.add(listCity.get(i).getName());
            }
        }
        return results;
    }

    private void reloadCity(String areaName, HttpServletResponse resp) throws Exception{
        CityBO cityBo = new CityBO();
        ArrayList<CityDTO> cities = cityBo.GetAllCityByAreaName(areaName);

        if(cities != null){
            PrintWriter out = resp.getWriter();
            int n = cities.size();
            for(int i = 0; i < n; i++){
                out.println(  "<tr>" +
                                    "<td id='td1'>" +
                                        cities.get(i).getName() +
                                    "</td>" +
                                    "<td>" +
                                    //../DetailArea?function=delete&city=
                                        "<a href = '../DetailArea?function=delete&city=" + cities.get(i).getName() + "'>Xóa</a>" +
                                    "</td>" +
                                    "<td>" +
                                        "<a href = '#'>Cập nhật</a>" +
                                    "</td>" +
                              "</tr>");
            }
        }
    }

    private void addCity(HttpServletRequest req, HttpServletResponse resp) throws Exception{
//        GET","../DetailArea?function=add&area="+area+
//                                    "&cityname="+cityName+"&cityCode="+cityCode, true);
//                    http.onreadystatechange = handleRePort;
                
        String cityName = (String) req.getParameter("cityname");
        String cityCode = (String) req.getParameter("citycode");
        String areaName = (String) req.getParameter("area");

        String report = "Thêm thành công Tỉnh/TP: " + cityName;

        CityBO cityBo = new CityBO();
        if(cityBo.checkCityExit(cityCode) == true){
            CityDTO city = cityBo.getCityByID(cityCode);
            report = "Tỉnh/Thành phố: " + city.getName() + " đã tồn tại với mã Tỉnh/TP: " + cityCode;
        }else{
            AreaBO areaBo = new AreaBO();
            AreaDTO area = areaBo.getAreaByName(areaName);
            String areaId = area.getId();
            CityDTO cityI = new CityDTO(cityCode, cityName, areaId);
            cityBo.InsertCity(cityI);
        }

        PrintWriter out = resp.getWriter();
        out.println(report);
    }

    private String deleteCity(HttpServletRequest req) throws Exception{        
        String cityName = (String) req.getParameter("city");
        WeatherCityBO wcb = new WeatherCityBO();
        CityBO cityBo = new CityBO();
        CityDTO cityDto = cityBo.getCityByName(cityName);
        wcb.DeleteByCityId(cityDto.getId());
        cityBo.DeleteCity(cityDto.getId());        

        AreaBO areaBo = new AreaBO();
        return areaBo.getAreaByID(cityDto.getAreaId()).getName();
    }
}
